package com.ourteam.system.api;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ourteam.frame.controller.AbstractTreeBuilderController;
import com.ourteam.frame.web.TreeParamModel;
import com.ourteam.frame.web.TreeViewNodeBean;
import com.ourteam.system.domain.SystemAction;
import com.ourteam.system.domain.SystemModule;
import com.ourteam.system.domain.SystemRole;
import com.ourteam.system.service.ISysRoleService;
import com.ourteam.system.service.SysRoleServiceFactory;

@Controller
@CrossOrigin
@RequestMapping("api/SYSTEM/sysRolePurViewModuleTree")
public class SystemRolePurViewModuleTreeBuilderAPI
		extends AbstractTreeBuilderController<SystemRolePurViewModuleTreeBuilder> {

	private static final ISysRoleService roleService = SysRoleServiceFactory.getSysRoleService();

	@RequestMapping("/buildTree/{roleId}")
	@ResponseBody
	public List<TreeViewNodeBean> buildTree(@PathVariable long roleId, @ModelAttribute TreeParamModel treeParamModel,
			@RequestParam(defaultValue = "0") int expandLevel, @RequestParam(required = false) String selectedNodeId,
			@RequestParam(required = true) String requestId, HttpServletRequest request) throws Exception {

		if (roleId == 0) {
			return new ArrayList<TreeViewNodeBean>(0);
		} else {

			final SystemRole systemRole = SysRoleServiceFactory.getSysRoleService().getSysRoleById(roleId);

			if (treeParamModel.getNodeConfigId() == null) {

				treeParamModel.setNodeid(String.valueOf(systemRole.getDomainId()));

			}

			request.setAttribute("roleId", systemRole.getId());

			return super.buildTree(treeParamModel, expandLevel, selectedNodeId, requestId, request);
		}

	}

	@Override
	protected SystemRolePurViewModuleTreeBuilder getTreeBuilder(HttpServletRequest request) {

		SystemModule[] modules;
		SystemAction[] actions;
		try {
			modules = roleService
					.getSysRoleModules(new long[] { Long.parseLong(request.getAttribute("roleId").toString()) });

			actions = roleService
					.getSysRoleActions(new long[] { Long.parseLong(request.getAttribute("roleId").toString()) });

			return new SystemRolePurViewModuleTreeBuilder(modules, actions);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}

	}

	@Override
	protected Object getInitParameter(HttpServletRequest request) {
		return null;
	}

}
